package org.zxl.iotest.netty.protobuf.util;

import com.google.protobuf.Message;
import com.google.protobuf.TextFormat;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangxiaolong
 * @date 2025-02-16 16:36
 **/
@Slf4j
public class ZxlMsgSendUtil {
    public static void sendMsg(Channel channel, Integer msgId, Message message){
        byte[] msgIdBytes = ByteUtils.intToBytesBE(msgId);

        Integer msgLength = 0;
        if(message != null){
            msgLength = message.toByteArray().length;
            byte[] msgLengthBytes = ByteUtils.intToBytesBE(msgLength);

            byte[] reqBytes = ByteUtils.concatenateByteArrays(msgIdBytes, msgLengthBytes, message.toByteArray());

            ByteBuf byteBuf = Unpooled.copiedBuffer(reqBytes);

            channel.writeAndFlush(byteBuf);
            log.info("sendMsg done, channelId:"+channel.id().toString()+";msgId:"+msgId+";message:"+TextFormat.printToString(message));
        }else {
            byte[] msgLengthBytes = ByteUtils.intToBytesBE(msgLength);

            byte[] reqBytes = ByteUtils.concatenateByteArrays(msgIdBytes, msgLengthBytes);
            ByteBuf byteBuf = Unpooled.copiedBuffer(reqBytes);

            channel.writeAndFlush(byteBuf);
            System.out.println("sendMsg done, channelId:"+channel.id().toString()+";msgId:"+msgId);
        }
    }
}
